package com.hkj.configcenter.admin.controller;

import com.hkj.configcenter.admin.url.ServiceUrl;
import com.hkj.configcenter.admin.vo.ResponseDTO;
import com.hkj.configcenter.core.Context;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
@Controller
public class ImportConfigController {

    @RequestMapping(ServiceUrl.CONFIG_CENTER_IMPORTFILE)
    @ResponseBody
    public ResponseDTO importFile(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return new ResponseDTO(-1, "文件为空");
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(), "utf-8"));
        importConfig(br);
        br.close();
        return new ResponseDTO(0, "导入成功");
    }

    @GetMapping(ServiceUrl.CONFIG_CENTER_IMPORTSTR)
    public String importStr() {
        return "config-center-importstr";
    }

    @RequestMapping(ServiceUrl.CONFIG_CENTER_IMPORTSTR)
    @ResponseBody
    public ResponseDTO importStr(@RequestParam("importStr") String importStr) throws Exception {
        if (StringUtils.isEmpty(importStr)) {
            return new ResponseDTO(-1, "文本为空");
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(importStr.getBytes()), "utf-8"));
        importConfig(br);
        br.close();
        return new ResponseDTO(0, "导入成功");
    }

    private void importConfig(BufferedReader br) throws IOException {
        String line;
        while ((line = br.readLine()) != null) {
            line = line.trim();
            log.info("【配置中心导入】==>{}", line);

            if (line.indexOf("=") <= 0) {
                log.info("【配置中心导入】无效行数==>{}", line);
                continue;
            }

            String[] key_value = initKeyValue(line);
            String value = key_value[1].replaceAll(Context.LINE_FEED, "\n");
            if (Context.zkClient.exists(key_value[0])) {
                Context.zkClient.writeData(key_value[0], value.getBytes("utf-8"));
            } else {
                Context.zkClient.createPersistent(key_value[0], value.getBytes("utf-8"));
            }
        }
    }

    private static String[] initKeyValue(String str) {
        int i = str.indexOf("=");
        return new String[]{str.substring(0, i), str.substring(i + 1, str.length())};
    }

}
